import xorEncryptionData from "./Tool/xor";
import httpUtils from "./XmlHttpTool";
import allVariableJs from "./allVariable";
import PlatformUtil from "./PlatformUtil";
import NumberView from "./NumberView";
const base64 = require('./Tool/base64.js');
cc.Class({
  extends: cc.Component,

  properties: {

    endAgainGameBtn: cc.Button,
    backGameMapBtn: cc.Button,
    backMarkView: cc.Node,
    closeBtn: cc.Button,
    endSound: {
      default: null,
      type: cc.AudioClip
    },
    endallview: cc.Node,
    bglightcoin: cc.Node,
    bglightNocoin: cc.Node,
    againGame: cc.Button,
    energyCompontent: NumberView,
    restBtn: cc.Button,
    preloadedRewardedVideo: "",
    showHubProjess: cc.Node,
    SvprogressPrefab: cc.Prefab,
    baseSource:""

  },


  againOnceGameClick: function () {

    if(allVariableJs.haveEnergy==0){

      if(cc.isValid(this.showHubProjess)){
          this.showHubProjess.destroy();
          }
          this.showHubProjess = cc.instantiate(this.SvprogressPrefab);
          this.node.addChild(this.showHubProjess);
          this.showHubProjess.getComponent('SVProgressView').init("Insufficient energy unable to participate")
      
          let finish = cc.callFunc(() => { 
      
          this.showHubProjess.destroy();
      
          }, this);
          let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(3), cc.fadeOut(1), finish);
          this.showHubProjess.runAction(action);

      return
  }

    var isshowAd= Math.random();  //可均衡获取0到9的随机整数。

    console.log("产生的随机数",isshowAd)
  
    var self = this

    if(isshowAd>0.7){

      self.endallview.active = false

      console.log("重新开始游戏不展示广告")
  
      cc.director.loadScene("GameSence", function () {
  
        var mainNode = cc.find("Canvas/backgroundtop")
  
        mainNode.getComponent("backgrould").onAgainGameSence();
  
      });
      return
    }

    allVariableJs.preloadedBrannerAd.showAsync()
      .then(function () {
        
        FBInstant.getInterstitialAdAsync(

          '1115286701982920_1147074248804165', 
        ).then(function (rewarded) {

          allVariableJs.preloadedBrannerAd = rewarded;

          return allVariableJs.preloadedBrannerAd.loadAsync();

        }).then(function () {
          console.log("插频广告数组", allVariableJs.preloadedBrannerAd)
        }).catch(function (err) {
          console.log("插屏广告加载错误", err);
          console.log("插屏广告变量", allVariableJs.preloadedBrannerAd);
        });
        console.log("结束游戏弹出插屏广告成功");
      
        self.endallview.active = false

        console.log("重新开始游戏")
    
        cc.director.loadScene("GameSence", function () {
    
          var mainNode = cc.find("Canvas/backgroundtop")
    
          mainNode.getComponent("backgrould").onAgainGameSence();
    
        });

       
      }).catch(function (e) {
        // 播放失败
        console.log("结束游戏弹出广告失败", e);
        // self.shareAddEnger();

        
        self.endallview.active = false

        console.log("重新开始游戏不展示广告")
    
        cc.director.loadScene("GameSence", function () {
    
          var mainNode = cc.find("Canvas/backgroundtop")
    
          mainNode.getComponent("backgrould").onAgainGameSence();
    
        });

      });

    var changebig = cc.scaleTo(0.2, 1.1);

    var finish = cc.callFunc(function () {

      var that = this
      var changesmail = cc.scaleTo(0.1, 1.0);

      var smaillfinish = cc.callFunc(function () {

      })

      var seq2 = cc.sequence(changesmail, smaillfinish)
      this.againGame.node.runAction(seq2)


    }, this);

    var seq = cc.sequence(changebig, finish)

    this.againGame.node.runAction(seq)

  },

  loadImg2Base64(url, callback) {

    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
    console.log("xhr.readyState " + xhr.readyState);
    console.log("xhr.status " + xhr.status);
    if (xhr.readyState === 4) {
    if (xhr.status === 200) {
        console.log("success");
    let data = new Uint8Array(xhr.response);
    let base = "data:image/png;base64," + base64.Base64.encodeArr(data);
    callback(base);
    }
    }
    };
    xhr.responseType = 'arraybuffer';
    xhr.open("GET", url, true);
    xhr.onerror = function(e) {
          
        console.log('转化图片错误',e)
    };
    xhr.send();
    },

  closeGameClick: function () {

    var changebig = cc.scaleTo(0.02, 1.2);

    var finish = cc.callFunc(function () {

      var changesmail = cc.scaleTo(0.08, 1.0);

      var smaillfinish = cc.callFunc(function () {

        cc.director.loadScene("StartGame");

      })

      var seq2 = cc.sequence(changesmail, smaillfinish)
      this.closeBtn.node.runAction(seq2)


    }, this);

    var seq = cc.sequence(changebig, finish)

    this.closeBtn.node.runAction(seq)

  },

  backGameMapClick: function () {

    var changebig = cc.scaleTo(0.2, 1.1);

    var finish = cc.callFunc(function () {

      var changesmail = cc.scaleTo(0.1, 1.0);

      var smaillfinish = cc.callFunc(function () {


      })

      var seq2 = cc.sequence(changesmail, smaillfinish)
      this.restBtn.node.runAction(seq2)


    }, this);

    var seq = cc.sequence(changebig, finish)

    this.restBtn.node.runAction(seq)

    var self = this
  
    if(this.preloadedRewardedVideo){
      this.preloadedRewardedVideo.showAsync()

      .then(function () {
        // 播放成功
        var _this = self
        httpUtils.httpPost("/marmot/ads_to_energy", {}, function (res) {

          var flagstr = res.flag_key + PlatformUtil.platform.params["appver"]
          var resultstr = xorEncryptionData.encryptionData(flagstr, PlatformUtil.platform.params)
          console.log("正常播放,可以发游戏奖励", flagstr)
          httpUtils.NhttpPost("/marmot/ads_to_energy", { "flag_key": resultstr, "keysid": res.keysid }, function (res) {
            console.log("广告体力请求接口", JSON.stringify(res))
            _this.energyCompontent.setText(parseInt(res["energy"]))
             cc.director.loadScene("GameSence", function () {
  
              var mainNode = cc.find("Canvas/backgroundtop")
        
              mainNode.getComponent("backgrould").onAgainGameSence();
        
            });

          }, function (failres) {
            console.log("广告体力请求接口失败", JSON.stringify(failres))
          })
        })
      }).catch(function (e) {

        console.log("广告播放失败", e);
        self.popBranerAdCode();  

      });
    }else{
      self.popBranerAdCode(); 
    }
  },


  popBranerAdCode:function(){

    var _this = this

    allVariableJs.preloadedBrannerAd.showAsync()
      .then(function () {
        
          
        httpUtils.httpPost("/marmot/ads_to_energy", {}, function (res) {

          var flagstr = res.flag_key + PlatformUtil.platform.params["appver"]
          var resultstr = xorEncryptionData.encryptionData(flagstr, PlatformUtil.platform.params)
          console.log("正常播放,可以发游戏奖励", flagstr)
        
          httpUtils.NhttpPost("/marmot/ads_to_energy", { "flag_key": resultstr, "keysid": res.keysid }, function (res) {
            console.log("广告体力请求接口", JSON.stringify(res))
              _this.endallview.active = false
            cc.director.loadScene("GameSence", function () {
  
              var mainNode = cc.find("Canvas/backgroundtop")
        
              mainNode.getComponent("backgrould").onAgainGameSence();
        
            });
        
          

          }, function (failres) {
            console.log("广告体力请求接口失败", JSON.stringify(failres))
          })
        })

        FBInstant.getInterstitialAdAsync(

          '1115286701982920_1147074248804165', 
        ).then(function (rewarded) {

          allVariableJs.preloadedBrannerAd = rewarded;

          return allVariableJs.preloadedBrannerAd.loadAsync();

        }).then(function () {
   
        }).catch(function (err) {
 
        });
        console.log("结束游戏弹出插屏广告成功");
           
      }).catch(function (e) {
        // 播放失败
        console.log("结束游戏弹出广告失败跳转分享", e);
  
        _this.shareAddEnger();
        
      });

  },


  shareAddEnger:function(){

    var self=this
    httpUtils.NhttpPost("/wxmp/marmot/share_msg",{"type":"link","link":"http://www.taoqi001.com/","title":"TapTapMoles","text":"Best Game Engine"},function(res){

    var _this=self
     var dataimageurl=res["image"]

     self.loadImg2Base64(dataimageurl,function(baseData){
 
       _this.baseSource=baseData
      FBInstant.shareAsync({

          intent: 'SHARE',
          image: _this.baseSource,
          text: 'X is asking for your help!',
          data: { myReplayData: '...' },
        
      }).then(function(data) {
   
          var that= _this

          httpUtils.NhttpPost("/wxmp/marmot/share",{},function(shareres){

              console.log('分享加体力',JSON.stringify(shareres))

        
              httpUtils.httpPost("/marmot/ads_to_energy", {}, function (res) {
      
                var flagstr = res.flag_key + PlatformUtil.platform.params["appver"]
                var resultstr = xorEncryptionData.encryptionData(flagstr, PlatformUtil.platform.params)
                console.log("正常播放,可以发游戏奖励", flagstr)
                httpUtils.NhttpPost("/marmot/ads_to_energy", { "flag_key": resultstr, "keysid": res.keysid }, function (res) {
                  console.log("广告体力请求接口", JSON.stringify(res))

                  that.energyCompontent.setText(parseInt(res["energy"]))

                  // that.endallview.active = false
                  // cc.director.loadScene("GameSence", function () {
        
                  //   var mainNode = cc.find("Canvas/backgroundtop")
              
                  //   mainNode.getComponent("backgrould").onAgainGameSence();
              
                  // });
      
                }, function (failres) {
                  console.log("广告体力请求接口失败", JSON.stringify(failres))
                })
              })

              if(cc.isValid(that.showHubProjess)){
                  that.showHubProjess.destroy();
                }
                that.showHubProjess = cc.instantiate(that.SvprogressPrefab);
                that.node.addChild(that.showHubProjess);
                that.showHubProjess.getComponent('SVProgressView').init("Get energy")
          
                 let finish = cc.callFunc(() => { 
                
                  that.showHubProjess.destroy();
              
                }, that);
              let action = cc.sequence(cc.fadeIn(0.6), cc.delayTime(4), cc.fadeOut(1), finish);
              that.showHubProjess.runAction(action);
   
          })
      
      });

  })

   })
  },

  onLoad() {


    this.sendStarHttp();

    this.backMarkView.on('touchstart', function (event) {
      console.log("点击结算背景层")
    }, this);

    var that = this

    cc.loader.load({ url: "https://h5.taoqi001.com/upload/201812/9834e678f3e8c6636778849dd055579c320f0900.png", type: 'png' }, function (err, img) {
      var mylogo = new cc.SpriteFrame(img);
      that.bglightcoin.getComponent(cc.Sprite).spriteFrame = mylogo;
      that.bglightcoin.height = 432
      that.bglightcoin.width = 712

      that.bglightNocoin.getComponent(cc.Sprite).spriteFrame = mylogo;
      that.bglightNocoin.height = 432
      that.bglightNocoin.width = 712

    });

    var isWatchad = FBInstant.getSupportedAPIs();
    console.log("广告api支持数组", isWatchad)

    var self = this
    FBInstant.getRewardedVideoAsync(
      '1115286701982920_1144618379049752', // Your Ad Placement Id
    ).then(function (rewarded) {
      self.preloadedRewardedVideo = rewarded;
      return self.preloadedRewardedVideo.loadAsync();
    }).then(function () {
      console.log("广告数组", self.preloadedRewardedVideo)
    }).catch(function (err) {
      console.log("广告加载错误", err);
      console.log("变量", self.preloadedRewardedVideo);
    });


  },
  sendStarHttp: function () {

    allVariableJs.isPlaying = false

    var resultDic = { "coins": allVariableJs.wawaCoinAddNumber, "game_id": allVariableJs.gameId, "stars": allVariableJs.starNumber, "hammers": allVariableJs.chuiziCount, "add_time": allVariableJs.timeCount, "game_time": allVariableJs.myPlayTimes }
    console.log("结束游戏", JSON.stringify(resultDic))

    this.current = cc.audioEngine.play(this.endSound, false, 1);

    var resultstr = xorEncryptionData.encryptionData(resultDic, PlatformUtil.platform.params)

    var that = this

    httpUtils.ThttpPost("/marmot/catch_callback", { "result": resultstr }, function (res) {

      console.log("上传分数", JSON.stringify(res))

      FBInstant.getLeaderboardAsync('mouseFriend')
        .then((leaderboard) => {
          console.log('--leaderboard setScoreAsync--')
          leaderboard.setScoreAsync(allVariableJs.starNumber, "");
        }, (reason) => {
          console.log(reason)
        });
   
      if (allVariableJs.wawaCoinAddNumber == 0) {

        if (parseInt(res["data"]["user_stars"]) < 0) {

          var starabs = Math.abs(res["data"]["user_stars"])
          that.node.getChildByName("gameStarLabel").getChildByName("miusstarNumber").getComponent("NumberView").setLeftText(parseInt(starabs), true)
          console.log("星币为负数", starabs)

        } else {
          that.node.getChildByName("gameStarLabel").getChildByName("starNumberCreator").getComponent("NumberView").setLeftText(parseInt(res["data"]["user_stars"]), false)
        }

      } else {
        if (parseInt(res["data"]["user_stars"]) < 0) {

          var starabs = Math.abs(res["data"]["user_stars"])
          console.log("星币为负数", starabs)
          that.node.getChildByName("gameStarLabel").getChildByName("miusstarNumber").getComponent("NumberView").setLeftText(parseInt(starabs), true)

        } else {
          that.node.getChildByName("gameStarLabel").getChildByName("starNumberCreator").getComponent("NumberView").setLeftText(parseInt(res["data"]["user_stars"]), false)
        }
        that.node.getChildByName("gameCoinLabel").getChildByName("coinNumberCreator").getComponent("NumberView").setLeftText(parseInt(res["data"]["coins"]), false)
      }

    }, function (failres) {

      console.log("上传分数错误", JSON.stringify(failres))
    })

  },

  start() {

  },

  // update (dt) {},
});
